class Photo < ActiveRecord::Base
  has_many :comments, :as => :commentable
  belongs_to :entry

	def chronological_next_in_entry
    return Photo.first(:conditions =>
			["entry_id = ? AND shot_date_time > ?", self.entry, self.shot_date_time],
			:order => 'shot_date_time ASC, filename ASC')
	end

	def chronological_previous_in_entry
		return Photo.first(:conditions =>
			["entry_id = ? AND shot_date_time < ?", self.entry, self.shot_date_time],
			:order => 'shot_date_time DESC, filename DESC')
	end

	def next_in_entry_by_filename
		return Photo.first(:conditions =>
			["entry_id = ? AND filename > ?", self.entry, self.filename],
			:order => 'filename ASC')
	end

	def chronological_last_in_entry?
		return self.chronological_next_in_entry == nil
	end

	def chronological_first_in_entry?
		return self.chronological_previous_in_entry == nil
	end

	def next_in_entry
		return Photo.first(:conditions => ["entry_id = ? AND id > ?", self.entry, self],
			:order => 'id ASC')
	end

	def previous_in_entry
		return Photo.first(:conditions => ["entry_id = ? AND id < ?", self.entry, self],
			:order => 'id DESC')
	end

	def Photo.entry_photos_by_datetime (entry)
		return Photo.find(:all, :conditions => ["entry_id = ?", entry],
			:order => 'photos.shot_date_time ASC')
	end

	def Photo.get_existing (entry, filename)
		return Photo.first(:conditions => ["entry_id = ? AND filename = ?",
			entry, filename])
	end

  def filepath
    return "public/#{self.entry.sourcedir}/#{self.filename}"
  end

	def relative_url
		return "/#{self.entry.sourcedir}/#{self.filename}"
	end

	def thumbnail_relative_url
		return "/#{self.entry.sourcedir}/thumbnails/#{self.filename}"
	end

  def last_in_entry?
    return Photo.last(:conditions => ["entry_id = ?", self.entry]) == self
  end

  def first_in_entry?
    return Photo.first(:conditions => ["entry_id = ?", self.entry]) == self
  end

	def owner
	  return self.entry.content_generator
	end

  def set_as_entry_thumbnail
    self.entry.photos.each do |p|
      p.is_entry_thumbnail = 0;
      p.save
    end
    self.is_entry_thumbnail = 1;
    self.save
  end

  def set_exif_data
    exif = EXIFR::JPEG.new("#{self.filepath}") 
    return if exif.nil?
      self.width		= exif.width
      self.height		= exif.height
      self.camera_brand		= exif.make
      self.camera_model		= exif.model
      self.exposure_time	= exif.exposure_time.to_s
      self.f_number		= exif.f_number.to_f
      self.iso_speed_rating	= exif.iso_speed_ratings
      self.shot_date_time	= exif.date_time
      self.focal_length		= exif.focal_length.to_f
    rescue
      false
  end

	def Photo.valid_filename? (filename)
		if filename =~ /^.*\.(jpe?g|gif|bmp|png|tiff?)$/i
			return true
		else
			return false
		end
	end
end
